package com.github.iogogogo.task.manager.schedule;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.support.CronExpression;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by tao.zeng on 2021/3/29.
 */
@Slf4j
@Component
public class ScheduledTaskService implements DisposableBean {

    private final Map<Runnable, ScheduledTask> scheduledTasks = new ConcurrentHashMap<>(16);

    @Autowired
    private TaskScheduler taskScheduler;

    /**
     * Gets scheduler.
     *
     * @return the scheduler
     */
    public TaskScheduler getScheduler() {
        return this.taskScheduler;
    }

    /**
     * Create cron task.
     *
     * @param task           the task
     * @param cronExpression the cron expression
     */
    public void addCronTask(Runnable task, String cronExpression) {
        // cron 表达式校验
        CronExpression.parse(cronExpression);
        addCronTask(new CronTask(task, cronExpression));
    }

    /**
     * Create cron task.
     *
     * @param cronTask the cron task
     */
    public void addCronTask(CronTask cronTask) {
        if (cronTask != null) {
            Runnable task = cronTask.getRunnable();
            if (this.scheduledTasks.containsKey(task)) {
                removeTask(task);
            }
            this.scheduledTasks.put(task, scheduleCronTask(cronTask));
        }
    }

    /**
     * Schedule cron task scheduled task.
     *
     * @param cronTask the cron task
     * @return the scheduled task
     */
    private ScheduledTask scheduleCronTask(CronTask cronTask) {
        ScheduledTask scheduledTask = new ScheduledTask();
        scheduledTask.future = this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());
        return scheduledTask;
    }

    /**
     * Remove task.
     *
     * @param task the task
     */
    public void removeTask(Runnable task) {
        ScheduledTask scheduledTask = this.scheduledTasks.remove(task);
        if (scheduledTask != null) scheduledTask.cancel();
    }

    /**
     * Trigger.
     *
     * @param beanName   the bean name
     * @param methodName the method name
     * @param param      the param
     */
    public void trigger(String beanName, String methodName, String param) {
        ScheduledTaskUtils.trigger(beanName, methodName, param);
    }

    @Override
    public void destroy() {
        for (ScheduledTask task : this.scheduledTasks.values()) {
            task.cancel();
        }
        this.scheduledTasks.clear();
    }
}
